package com.example.abe.diandi.collect.activity;

import android.content.Intent;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;

import com.example.BindView;
import com.example.OnClick;
import com.example.abe.diandi.R;
import com.example.abe.diandi.base.BaseActivity;
import com.example.abe.diandi.collect.adapter.CollectTrendDelegate;
import com.example.abe.diandi.collect.model.CollectTrendListModel;
import com.example.abe.diandi.main.AppConfig;
import com.example.abe.diandi.nohttp.ApiUtil;
import com.example.abe.diandi.nohttp.CallServer;
import com.example.abe.diandi.nohttp.HttpListener;
import com.example.abe.diandi.trends.activity.TrendsShowActivity;
import com.example.abe.diandi.trends.model.TrendModel;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.yanzhenjie.nohttp.NoHttp;
import com.yanzhenjie.nohttp.RequestMethod;
import com.yanzhenjie.nohttp.rest.Request;
import com.yanzhenjie.nohttp.rest.Response;

import java.util.ArrayList;
import java.util.List;

import example.abe.com.framework.recycleview.adapter.BaseAdapter;
import example.abe.com.framework.refresh.OnLoadMoreListener;
import example.abe.com.framework.refresh.OnRefreshListener;
import example.abe.com.framework.refresh.SwipeToLoadLayout;
import example.abe.com.framework.util.TimeUtil;
import example.abe.com.framework.util.ToastUtil;

import static android.support.v7.widget.RecyclerView.SCROLL_STATE_IDLE;
import static com.example.abe.diandi.nohttp.ApiUtil.METHOD;
import static com.example.abe.diandi.nohttp.ApiUtil.M_TREND_GET_COLLECT_TRENDS_LIST;
import static com.example.abe.diandi.nohttp.ApiUtil.SERVICE;
import static com.example.abe.diandi.nohttp.ApiUtil.S_TREND;
import static com.yanzhenjie.nohttp.NoHttp.getContext;

public class CollectActivity extends BaseActivity implements OnRefreshListener, OnLoadMoreListener {

    @BindView(R.id.act_collect_swipe_to_load)
    protected SwipeToLoadLayout mSwipeToLoadLayout;

    @BindView(R.id.swipe_target)
    protected RecyclerView mRv;

    @BindView(R.id.act_collect_tv_time)
    protected TextView mTvTime;

    private String mStartTrendId;

    private List<TrendModel> mListData;

    private BaseAdapter<TrendModel> mAdapter;

    private LinearLayoutManager mLinearLayoutManager;


    @Override
    public int getLayoutID() {
        return R.layout.activity_collect;
    }

    @Override
    public void initData() {
        mListData = new ArrayList<>();
        mLinearLayoutManager = new LinearLayoutManager(getContext());
    }

    @Override
    public void initView() {
        mSwipeToLoadLayout.setOnRefreshListener(this);
        mSwipeToLoadLayout.setOnLoadMoreListener(this);

        mAdapter = new BaseAdapter<>(getContext(), mListData);
        mAdapter.addItemViewDelegate(new CollectTrendDelegate());
        mRv.setLayoutManager(mLinearLayoutManager);
        mRv.setAdapter(mAdapter);
        mRv.setOnScrollListener(onScrollListener);

        mSwipeToLoadLayout.setRefreshing(true);

        mAdapter.setOnItemClickListener(onItemClickListener);
    }

    @Override
    public void onSideSlipEvent(){
        finish();
    }

    private RecyclerView.OnScrollListener onScrollListener = new RecyclerView.OnScrollListener() {
        @Override
        public void onScrollStateChanged(RecyclerView recyclerView, int newState){
            //停止滑动时调用
            if (newState == SCROLL_STATE_IDLE && recyclerView.getChildAt(0) != null){
                int position = (Integer)recyclerView.getChildAt(0).getTag();
                TrendModel trendModel = mListData.get(position);
                mTvTime.setText(TimeUtil.getStrTimeCH(trendModel.getTime(), "yyyy年MM月"));
            }
        }
    };

    private BaseAdapter.OnItemClickListener onItemClickListener = new BaseAdapter.OnItemClickListener<TrendModel>() {
        @Override
        public void onItemClick(View view, RecyclerView.ViewHolder holder, TrendModel data, int position) {
            Intent intent = new Intent(CollectActivity.this, TrendsShowActivity.class);
            intent.putExtra(TrendsShowActivity.NOTE_MODEL_DATA, mListData.get(position));
            startActivity(intent);
        }

        @Override
        public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, TrendModel data, int position) {
            return false;
        }
    };

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onRefresh() {
        mStartTrendId = "-1";
        mListData.clear();
        updateTrendList(mStartTrendId);
    }

    @Override
    public void onLoadMore() {
        mStartTrendId = mListData.get(mListData.size()-1).getId();
        updateTrendList(mStartTrendId);
    }

    @OnClick(R.id.act_collect_iv_back)
    protected void onBackClick(){
        finish();
    }

    private void updateTrendList(String startTrendId){
        Request<String> request = NoHttp.createStringRequest(ApiUtil.URL, RequestMethod.POST);
        request.add(SERVICE, S_TREND)
                .add(METHOD, M_TREND_GET_COLLECT_TRENDS_LIST)
                .add("userId", AppConfig.getUserModel().getId())
                .add("startTrendId", startTrendId)
                .add("limit", 10);
        CallServer.getInstance().add(CollectActivity.this, false, request, new HttpListener<String>() {

            @Override
            public void onSucceed(int what, Response<String> response) {
                JsonObject jsonObj = new JsonParser().parse(response.get()).getAsJsonObject();
                Boolean isSuccess = jsonObj.get("success").getAsBoolean();
                if (isSuccess) {
                    JsonObject data = jsonObj.getAsJsonObject("data");
                    CollectTrendListModel model = new Gson().fromJson(data, CollectTrendListModel.class);
                    mListData.addAll(model.getList());
                    mAdapter.notifyDataSetChanged();
                    if (mListData.size() > 0){
                        mTvTime.setVisibility(View.VISIBLE);
                        mTvTime.setText(TimeUtil.getStrTimeCH(mListData.get(0).getTime(), "yyyy年MM月"));
                    }
                }
                mSwipeToLoadLayout.setRefreshing(false);
                mSwipeToLoadLayout.setLoadingMore(false);
            }

            @Override
            public void onFailed(int what, Response<String> response) {
                mSwipeToLoadLayout.setRefreshing(false);
                mSwipeToLoadLayout.setLoadingMore(false);
                ToastUtil.makeText("加载失败");
            }
        });
    }
}